<template>
  <div class="report-notifications-page" v-loading="loading">
    <ReportsSearchCard title="搜索与筛选">
      <el-form :model="searchForm" class="search-form" label-width="100px">
        <div class="search-form-content">
          <div class="search-form-fields">
            <el-form-item label="通知名称">
              <el-input
                v-model="searchForm.name"
                clearable
                placeholder="输入通知名称搜索"
                style="width: 200px"
              />
            </el-form-item>

            <el-form-item label="渠道类型">
              <el-select
                v-model="searchForm.channel_type"
                clearable
                placeholder="全部渠道"
                style="width: 160px"
                popper-class="batch-dialog-select-popper"
                popper-append-to-body
              >
                <el-option label="全部" value="" />
                <el-option label="企业微信" value="wecom" />
                <el-option label="钉钉" value="dingtalk" />
                <el-option label="飞书" value="feishu" />
                <el-option label="邮件" value="email" />
                <el-option label="自定义" value="custom" />
              </el-select>
            </el-form-item>

            <el-form-item label="状态">
              <el-select
                v-model="searchForm.is_active"
                clearable
                placeholder="全部状态"
                style="width: 160px"
                popper-class="batch-dialog-select-popper"
                popper-append-to-body
              >
                <el-option label="全部" value="" />
                <el-option label="启用" value="true" />
                <el-option label="禁用" value="false" />
              </el-select>
            </el-form-item>
          </div>

          <div class="search-form-actions">
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button type="warning" @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
            <el-button type="success" @click="handleCreate">
              <el-icon><Plus /></el-icon>
              新建通知
            </el-button>
          </div>
        </div>
      </el-form>
    </ReportsSearchCard>

    <ReportsTableCard>
      <template #title>
        <el-icon><List /></el-icon>
        <span>通知列表</span>
      </template>
      <template #actions>
        <el-button type="success" @click="handleRefresh" class="refresh-btn" :loading="loading" size="small">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
        <div class="table-info">
          <div class="pagination-control-wrapper clickable" @click="togglePagination">
            <span class="page-count">本页 {{ tableData.length }} 条</span>
            <div class="divider"></div>
            <span class="pagination-info">
              {{ pagination.page }}/{{ Math.ceil(pagination.total / pagination.size) || 1 }}
            </span>
            <el-icon class="pagination-toggle-icon">
              <ArrowUp v-if="paginationVisible" />
              <ArrowDown v-else />
            </el-icon>
          </div>
        </div>
      </template>

      <el-table
        :data="tableData"
        v-loading="loading"
        @sort-change="handleSortChange"
        :default-sort="{ prop: 'updated_at', order: 'descending' }"
        class="enhanced-table"
        style="width: 100%"
        :height="600"
        table-layout="fixed"
        :stripe="false"
        :border="false"
      >
        <el-table-column prop="name" label="名称" min-width="150" show-overflow-tooltip fixed="left" />

        <el-table-column label="渠道类型" min-width="120">
          <template #default="{ row }">
            <el-tag :type="getChannelTagType(row.channel_type)" size="small">
              {{ getChannelName(row.channel_type) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="webhook_url" label="通知地址" min-width="250" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.webhook_url || '-' }}
          </template>
        </el-table-column>

        <el-table-column prop="description" label="描述" min-width="180" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.description || '-' }}
          </template>
        </el-table-column>

        <el-table-column label="状态" min-width="80">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'info'" size="small">
              {{ row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" min-width="180" show-overflow-tooltip sortable="custom" prop="created_at">
          <template #default="{ row }">
            {{ formatDateTime(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="更新时间" min-width="180" show-overflow-tooltip sortable="custom" prop="updated_at">
          <template #default="{ row }">
            {{ formatDateTime(row.updated_at) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-tooltip content="查看" placement="top">
                <el-button
                  type="success"
                  size="small"
                  @click="handleView(row)"
                  circle
                >
                  <el-icon><View /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="编辑" placement="top">
                <el-button
                  type="primary"
                  size="small"
                  @click="handleEdit(row)"
                  circle
                >
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="发送测试" placement="top">
                <el-button
                  type="warning"
                  size="small"
                  @click="handleSendTest(row)"
                  circle
                >
                  <el-icon><VideoPlay /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button
                  type="danger"
                  size="small"
                  plain
                  @click="handleDelete(row)"
                  circle
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <template #pagination>
        <transition name="pagination-slide">
          <div v-show="paginationVisible" class="pagination-section">
            <el-pagination
              v-model:current-page="pagination.page"
              v-model:page-size="pagination.size"
              :total="pagination.total"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @current-change="fetchData"
              @size-change="fetchData"
              background
            />
          </div>
        </transition>
      </template>
    </ReportsTableCard>

    <el-dialog
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      append-to-body
      destroy-on-close
      class="unified-dialog"
    >
      <template #header>
        <DialogHeader
          :icon="dialogType === 'create' ? Plus : Edit"
          :title="dialogType === 'create' ? '新建通知' : '编辑通知'"
          :description="formData.name || ''"
          type="primary"
        />
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="输入通知名称" />
        </el-form-item>

        <el-form-item label="渠道类型" prop="channel_type">
          <el-select
            v-model="formData.channel_type"
            placeholder="选择渠道类型"
            style="width: 100%"
            popper-class="batch-dialog-select-popper"
            popper-append-to-body
          >
            <el-option label="企业微信" value="wecom" />
            <el-option label="钉钉" value="dingtalk" />
            <el-option label="飞书" value="feishu" />
            <el-option label="邮件" value="email" />
            <el-option label="自定义" value="custom" />
          </el-select>
        </el-form-item>

        <el-form-item
          v-if="channelTypesRequireWebhook.includes(formData.channel_type)"
          label="通知地址"
          prop="webhook_url"
        >
          <el-input v-model="formData.webhook_url" placeholder="输入通知地址" />
        </el-form-item>

        <el-form-item
          v-if="formData.channel_type === 'email'"
          label="收件人"
          prop="email_recipients"
        >
          <el-select
            v-model="formData.email_recipients"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="输入或选择邮箱地址"
            style="width: 100%"
            popper-class="batch-dialog-select-popper"
            popper-append-to-body
          />
        </el-form-item>

        <el-form-item label="描述">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="输入描述信息（可选）"
          />
        </el-form-item>

        <el-form-item label="状态">
          <el-switch
            v-model="formData.is_active"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="detailDialogVisible"
      width="800px"
      :close-on-click-modal="false"
      append-to-body
      class="unified-dialog"
    >
      <template #header>
        <DialogHeader
          :icon="View"
          title="通知详情"
          :description="currentDetail?.name || ''"
          type="success"
        />
      </template>

      <div v-if="currentDetail" class="dialog-content">
        <el-descriptions title="基础信息" :column="2" border>
          <el-descriptions-item label="名称">
            {{ currentDetail.name }}
          </el-descriptions-item>
          <el-descriptions-item label="渠道类型">
            <el-tag :type="getChannelTagType(currentDetail.channel_type)" size="small">
              {{ getChannelName(currentDetail.channel_type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item
            v-if="channelTypesRequireWebhook.includes(currentDetail.channel_type)"
            label="通知地址"
            :span="2"
          >
            {{ currentDetail.webhook_url || '-' }}
          </el-descriptions-item>
          <el-descriptions-item
            v-if="currentDetail.channel_type === 'email'"
            label="收件人"
            :span="2"
          >
            <el-tag
              v-for="email in (currentDetail.email_recipients || [])"
              :key="email"
              size="small"
              style="margin-right: 8px"
            >
              {{ email }}
            </el-tag>
            <span v-if="!currentDetail.email_recipients || currentDetail.email_recipients.length === 0">-</span>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentDetail.is_active ? 'success' : 'info'" size="small">
              {{ currentDetail.is_active ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDateTime(currentDetail.created_at) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ formatDateTime(currentDetail.updated_at) }}
          </el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">
            {{ currentDetail.description || '-' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleEditFromDetail">
            <el-icon><Edit /></el-icon>
            编辑通知
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, List, ArrowUp, ArrowDown, View, Edit, VideoPlay, Delete, Plus } from '@element-plus/icons-vue'
import ReportsSearchCard from '../components/layout/ReportsSearchCard.vue'
import ReportsTableCard from '../components/layout/ReportsTableCard.vue'
import DialogHeader from '@/components/DialogHeader.vue'
import api from '@/utils/api'
import { createLogger } from '@/utils/logger'

const componentLogger = createLogger('ReportNotificationsPage')

const loading = ref(false)
const tableData = ref([])
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})
const paginationVisible = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('create')
const detailDialogVisible = ref(false)
const currentDetail = ref(null)
const formRef = ref(null)
const submitting = ref(false)

const channelTypesRequireWebhook = ['wecom', 'dingtalk', 'feishu', 'custom']

const formData = reactive({
  id: null,
  name: '',
  channel_type: 'wecom',
  webhook_url: '',
  email_recipients: [],
  description: '',
  is_active: true
})

const searchForm = reactive({
  name: '',
  channel_type: '',
  is_active: '',
  sortField: 'updated_at',
  sortOrder: 'desc'
})

const formRules = {
  name: [{ required: true, message: '请输入通知名称', trigger: 'blur' }],
  channel_type: [{ required: true, message: '请选择渠道类型', trigger: 'change' }],
  webhook_url: [{
    validator: (_, value, callback) => {
      if (channelTypesRequireWebhook.includes(formData.channel_type)) {
        if (!value) {
          callback(new Error('请输入通知地址'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    },
    trigger: 'blur'
  }],
  email_recipients: [{
    validator: (_, value, callback) => {
      if (formData.channel_type === 'email' && (!value || value.length === 0)) {
        callback(new Error('请输入至少一个收件人邮箱'))
      } else {
        callback()
      }
    },
    trigger: 'change'
  }]
}

const getChannelName = (type) => {
  const map = {
    wecom: '企业微信',
    dingtalk: '钉钉',
    feishu: '飞书',
    email: '邮件',
    custom: '自定义'
  }
  return map[type] || type
}

const getChannelTagType = (type) => {
  const map = {
    wecom: 'success',
    dingtalk: 'primary',
    feishu: 'warning',
    email: 'info',
    custom: ''
  }
  return map[type] || ''
}

const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '-'

  if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(dateTimeStr)) {
    return dateTimeStr
  }

  if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(dateTimeStr) && !dateTimeStr.includes('Z') && !dateTimeStr.match(/[+-]\d{2}:\d{2}$/)) {
    const match = dateTimeStr.match(/^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2})/)
    if (match) {
      return `${match[1]} ${match[2]}`
    }
  }

  try {
    const date = new Date(dateTimeStr)
    if (isNaN(date.getTime())) {
      return dateTimeStr
    }

    const formatter = new Intl.DateTimeFormat('zh-CN', {
      timeZone: 'Asia/Shanghai',
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    })

    const parts = formatter.formatToParts(date)
    const year = parts.find(p => p.type === 'year').value
    const month = parts.find(p => p.type === 'month').value
    const day = parts.find(p => p.type === 'day').value
    const hour = parts.find(p => p.type === 'hour').value
    const minute = parts.find(p => p.type === 'minute').value
    const second = parts.find(p => p.type === 'second').value

    return `${year}-${month}-${day} ${hour}:${minute}:${second}`
  } catch (error) {
    return dateTimeStr
  }
}

const togglePagination = () => {
  paginationVisible.value = !paginationVisible.value
}

const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size
    }

    if (searchForm.name) params.name = searchForm.name
    if (searchForm.channel_type) params.channel_type = searchForm.channel_type
    if (searchForm.is_active) params.is_active = searchForm.is_active

    if (searchForm.sortField) {
      params.sort_field = searchForm.sortField
      params.sort_order = searchForm.sortOrder
    }

    const response = await api.get('/reports/webhook-library', { params })
    if (response.data.success) {
      tableData.value = response.data.data.rows
      pagination.total = response.data.data.total
      componentLogger.info('通知库数据加载成功', { count: tableData.value.length })
    }
  } catch (error) {
    componentLogger.error('获取通知库失败', error)
    ElMessage.error('获取通知库失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  fetchData()
}

const handleReset = () => {
  searchForm.name = ''
  searchForm.channel_type = ''
  searchForm.is_active = ''
  searchForm.sortField = 'updated_at'
  searchForm.sortOrder = 'desc'
  pagination.page = 1
  fetchData()
}

const handleSortChange = ({ prop, order }) => {
  if (prop) {
    searchForm.sortField = prop
    searchForm.sortOrder = order === 'ascending' ? 'asc' : 'desc'
    fetchData()
  }
}

const handleRefresh = () => {
  fetchData()
  ElMessage.success('刷新成功')
}

const handleCreate = () => {
  dialogType.value = 'create'
  Object.assign(formData, {
    id: null,
    name: '',
    channel_type: 'wecom',
    webhook_url: '',
    email_recipients: [],
    description: '',
    is_active: true
  })
  dialogVisible.value = true
}

const fetchNotificationDetail = async (id) => {
  const response = await api.get(`/reports/webhook-library/${id}`)
  return response.data.data
}

const handleView = async (row) => {
  try {
    currentDetail.value = await fetchNotificationDetail(row.id)
    detailDialogVisible.value = true
  } catch (error) {
    componentLogger.error('查看通知详情失败', error)
    ElMessage.error('获取通知详情失败')
  }
}

const handleEdit = async (row) => {
  try {
    dialogType.value = 'edit'
    const data = await fetchNotificationDetail(row.id)
    Object.assign(formData, {
      ...data,
      email_recipients: data.email_recipients || [],
      is_active: data.is_active === 1 || data.is_active === true
    })
    dialogVisible.value = true
  } catch (error) {
    componentLogger.error('编辑通知加载失败', error)
    ElMessage.error('获取通知信息失败')
  }
}

const handleEditFromDetail = () => {
  if (currentDetail.value) {
    handleEdit(currentDetail.value)
    detailDialogVisible.value = false
  }
}

const handleSubmit = async () => {
  const form = formRef.value
  if (!form) return
  const valid = await form.validate().catch(() => false)
  if (!valid) return

  submitting.value = true
  try {
    const payload = {
      name: formData.name,
      channel_type: formData.channel_type,
      description: formData.description,
      is_active: formData.is_active ? 1 : 0
    }

    if (channelTypesRequireWebhook.includes(formData.channel_type)) {
      payload.webhook_url = formData.webhook_url
    }

    if (formData.channel_type === 'email') {
      payload.email_recipients = formData.email_recipients
    }

    if (dialogType.value === 'create') {
      await api.post('/reports/webhook-library', payload)
      ElMessage.success('创建成功')
    } else {
      await api.put(`/reports/webhook-library/${formData.id}`, payload)
      ElMessage.success('更新成功')
    }

    dialogVisible.value = false
    fetchData()
  } catch (error) {
    componentLogger.error('保存通知失败', error)
    ElMessage.error(error.response?.data?.message || '保存失败')
  } finally {
    submitting.value = false
  }
}

const handleSendTest = async (row) => {
  try {
    const response = await api.post(`/reports/webhook-library/${row.id}/test`)
    if (response.data.success) {
      ElMessage.success('测试通知已发送')
    } else {
      ElMessage.error(response.data.message || '测试失败')
    }
  } catch (error) {
    componentLogger.error('测试通知失败', error)
    ElMessage.error(error.response?.data?.message || '测试失败')
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除通知“${row.name}”吗？删除后相关配置将无法使用该通知。`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await api.delete(`/reports/webhook-library/${row.id}`)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      componentLogger.error('删除通知失败', error)
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.report-notifications-page {
  padding: 0;
}

.search-form-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
}

.search-form-fields {
  display: flex;
  gap: 20px;
  flex: 1;
}

.search-form-fields .el-form-item {
  margin-bottom: 0;
}

.search-form-actions {
  display: flex;
  gap: 10px;
  white-space: nowrap;
}

.table-info {
  display: flex;
  align-items: center;
}

.refresh-btn {
  background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
  border: none;
  border-radius: 8px;
  color: #fff;
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-weight: 500;
}

.refresh-btn:hover {
  background: linear-gradient(135deg, #85CE61 0%, #67C23A 100%);
  box-shadow: 0 6px 20px rgba(103, 194, 58, 0.4);
  transform: translateY(-2px);
  color: #fff;
}

.pagination-control-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
  background: rgba(64, 158, 255, 0.08);
  border: 1px solid rgba(64, 158, 255, 0.2);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  user-select: none;
  font-size: 12px;
  height: 24px;
}

.pagination-control-wrapper:hover {
  background: rgba(64, 158, 255, 0.12);
  border-color: rgba(64, 158, 255, 0.3);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}

.page-count {
  font-size: 12px;
  font-weight: 500;
  color: #909399;
  line-height: 1;
}

.divider {
  width: 1px;
  height: 12px;
  background: rgba(64, 158, 255, 0.3);
  margin: 0 2px;
}

.pagination-info {
  font-size: 12px;
  font-weight: 500;
  color: #409eff;
  letter-spacing: 0.5px;
  min-width: 24px;
  text-align: center;
  line-height: 1;
}

.pagination-toggle-icon {
  font-size: 12px;
  color: #409eff;
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.pagination-section {
  padding: 16px;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
}

.pagination-section .el-pagination {
  display: flex;
  justify-content: center;
}

.pagination-slide-enter-active,
.pagination-slide-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.pagination-slide-enter-from,
.pagination-slide-leave-to {
  opacity: 0;
  max-height: 0;
  overflow: hidden;
}

.pagination-slide-enter-to,
.pagination-slide-leave-from {
  opacity: 1;
  max-height: 200px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: nowrap;
  white-space: nowrap;
  justify-content: flex-start;
  align-items: center;
  min-width: 220px;
}

.action-buttons :deep(.el-button) {
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
  width: 32px;
  height: 32px;
  padding: 0;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.action-buttons :deep(.el-button:hover) {
  transform: translateY(-2px) scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.action-buttons :deep(.el-button:active) {
  transform: translateY(0) scale(0.98);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
